from fastapi import APIRouter, Depends, HTTPException
from typing import Dict, Any

from app.api.deps import get_current_user
from app.schemas.memory import (
    RPCRequest,
    RPCResponse,
    RecordMemoryRequest,
    RetrieveMemoryRequest,
    MemoryConfig
)
from app.services.memory_service import MemoryService

router = APIRouter()

@router.post("/rpc")
async def handle_memory_rpc(
    request: RPCRequest,
    current_user: str = Depends(get_current_user)
) -> RPCResponse:
    """处理记忆相关的 RPC 请求"""
    try:
        method = request.method
        params = request.params or {}
        result: Dict[str, Any] = {}

        if method == "memory/configure":
            config = MemoryConfig(**params)
            memory = await MemoryService.get_memory_instance(
                user_id=str(current_user.id),
                config=config
            )
            result = {"status": "success", "message": "Memory configured successfully"}

        elif method == "memory/record":
            record_request = RecordMemoryRequest(**params)
            result = await MemoryService.record_memory(
                user_id=str(current_user.id),
                thinking=record_request.thinking,
                content=record_request.content,
                memory_type=record_request.memory_type,
                infer=record_request.infer,
                agent_name=params.get("agent_name"),
                run_name=params.get("run_name")
            )

        elif method == "memory/retrieve":
            retrieve_request = RetrieveMemoryRequest(**params)
            result = await MemoryService.retrieve_memory(
                user_id=str(current_user.id),
                keywords=retrieve_request.keywords,
                limit=retrieve_request.limit,
                memory_type=params.get("memory_type"),
                agent_name=params.get("agent_name"),
                run_name=params.get("run_name")
            )

        else:
            raise HTTPException(
                status_code=400,
                detail=f"Unknown method: {method}"
            )

        return RPCResponse(
            jsonrpc="2.0",
            id=request.id,
            result=result
        )

    except Exception as e:
        return RPCResponse(
            jsonrpc="2.0",
            id=request.id,
            error={
                "code": -32603,
                "message": "Internal error",
                "data": str(e)
            }
        )